# coding: utf-8
from PySide6.QtCore import Qt
from qfluentwidgets import IconWidget, TitleLabel, Pivot

from common import cfg, SingleIcon, APP_NAME
from components import SlidingStackedWidget, Alert, VerticalScrollArea
from .about_setting_widget import AboutSettingWidget
from .app_setting_widget import AppSettingWidget
from .theme_style_widget import ThemeStyleWidget


class SettingInterface(VerticalScrollArea):
    """ Setting interface """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.iconWidget = IconWidget(SingleIcon.LOGO_PNG, self)
        self.titleLabel = TitleLabel(APP_NAME, self)
        self.pivot = Pivot(self)
        self.stackedWidget = SlidingStackedWidget(self)

        self.themeStyle = ThemeStyleWidget(self.stackedWidget)
        self.appSetting = AppSettingWidget(self.stackedWidget)
        self.aboutSetting = AboutSettingWidget(self.stackedWidget)

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName('SettingInterface')
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)

        self.pivot.addItem('ThemeStyle', '主题样式')
        self.pivot.addItem('Download', '应用设置')
        self.pivot.addItem('About', '关于')
        self.pivot.setCurrentItem('ThemeStyle')
        self.pivot.setItemFontSize(14)
        self.pivot.setFixedWidth(400)

        self.stackedWidget.addWidget(self.themeStyle)
        self.stackedWidget.addWidget(self.appSetting)
        self.stackedWidget.addWidget(self.aboutSetting)

        self.iconWidget.setFixedSize(100, 100)
        self.setLayoutContentsMargins(100, 11, 100, 11)
        self.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        self.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignHCenter)
        self.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignHCenter)
        self.addSpacing(20)
        self.addWidget(self.pivot, 0, Qt.AlignmentFlag.AlignHCenter)
        self.addWidget(self.stackedWidget, 1)

        self.pivot.currentItemChanged.connect(self.onPivotChanged)
        cfg.appRestartSig.connect(lambda: Alert.info('应用设置已更改，请重启应用以应用更改'))

    def onPivotChanged(self, routeKey: str):
        mapping = {
            'ThemeStyle': self.themeStyle,
            'Download': self.appSetting,
            'About': self.aboutSetting
        }
        self.stackedWidget.setCurrentWidget(mapping[routeKey])

    def resizeEvent(self, e) -> None:
        self.stackedWidget.setMaximumWidth(self.width() - 200)
        super().resizeEvent(e)